import { CanActivate, ExecutionContext, ForbiddenException, HttpException, Inject, Injectable } from "@nestjs/common";
import { Observable } from "rxjs";
import dayjs from "dayjs";
import CryptoJs from "crypto-js";
// import { PanCodeService } from "src/modules/system/pan/pan-code/pan-code.service";
import { parseSecretKeyFormat, parseSecretKeyTime } from "@/config";

@Injectable()
// 校验卡密是否过期
export class PanCodeGuard implements CanActivate {
    constructor(
        // @Inject(PanCodeService)
        // private readonly panCodeService: PanCodeService
    ) {
        
    }
    
    async canActivate(
        context: ExecutionContext
    ): Promise<boolean> {
        const request = context.switchToHttp().getRequest();
        console.log("request.headers", request.headers);
        console.log("request.url", request.url);
        const bSign = `${+request.headers.code}${parseSecretKeyTime()}`;
        console.log("bSign", bSign);
        const aseKey = CryptoJs.MD5(bSign).toString(); // 'code' + dayjs(Date.now()).format('YYYY-MM-DD HH');
        console.log("aseKey", aseKey);
        const shouldSign = encodeURIComponent(CryptoJs.AES.encrypt(bSign, aseKey).toString());
        console.log("----------------------------------");
        console.log("head--sign", request.headers.sign);
        console.log("shouldSign", shouldSign);
        console.log("----------------------------------");
        const code = CryptoJs.AES.decrypt(decodeURIComponent(request.headers.sign), aseKey).toString(CryptoJs.enc.Utf8);
        console.log("code----", code);
        // 查询code信息
        // const res = await this.panCodeService.findPanCodeByCode(code);
        // request.panCode = res;
        // console.log("res----", res);
        //
        // //判断
        // if (!res) throw new HttpException("页面停留时间过长,请点击或者刷新重试", 441);
        // if (["/panCode/findCodeInfo"].includes(request.path)) return true;
        // if (!res.status) throw new ForbiddenException("卡密已被禁用,请联系管理员");
        // if (new Date() > new Date(res.expirationTime)) throw new ForbiddenException("卡密已失效过期,请重新购买卡密");
        // //测试永久次数卡
        // if (code === "88488848") return true;
        // //次数限制判断
        // if (+res.todayResidueFileNum <= 0) throw new ForbiddenException("今日解析文件次数已用完,请明日再试,或购买新卡");
        // if (+res.todayResidueNum <= 0) throw new ForbiddenException("今日解析次数已用完,请明日再试,或购买新卡");
        return true;
    }
}
